﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using be.belgium.eid;
using System.Globalization;
using Toolkit;

namespace CardReader {
  public static class Reader {

    public static BasicCardData ReadCard( ) {
      BasicCardData basicData = new BasicCardData( );

      try {
        BEID_ReaderSet.releaseSDK( );

        BEID_ReaderContext readerContext = BEID_ReaderSet.instance( ).getReader( );
        if ( readerContext.isCardPresent( ) ) {
          if ( readerContext.getCardType( ) == BEID_CardType.BEID_CARDTYPE_EID
             || readerContext.getCardType( ) == BEID_CardType.BEID_CARDTYPE_FOREIGNER
             || readerContext.getCardType( ) == BEID_CardType.BEID_CARDTYPE_KIDS ) {

            basicData = ReadEid( readerContext );
          }
        }



      } catch ( BEID_ExNoReader ex ) {
        throw;
      } finally {
        BEID_ReaderSet.releaseSDK( );
      }

      return basicData;
    }

    private static BasicCardData ReadEid( BEID_ReaderContext readerContext ) {
      BasicCardData basicData = new BasicCardData( );

      BEID_EIDCard card = readerContext.getEIDCard( );
      BEID_EId idDocument = card.getID( );
      BEID_Picture picture = card.getPicture( );

      basicData.FirstName = idDocument.getFirstName( );
      basicData.Name = idDocument.getSurname( );
      basicData.Birthday = DateTime.Parse( idDocument.getDateOfBirth( ) );
      basicData.Street = idDocument.getStreet( );
      basicData.Zipcode = idDocument.getZipCode( );
      basicData.City = idDocument.getMunicipality( );
      basicData.CountryCode = idDocument.getCountry( ).ToUpper( CultureInfo.CurrentCulture );
      basicData.NationalNumber = idDocument.getNationalNumber( );
      basicData.Photo = GraphicTools.Convert.ByteArrayToImage( picture.getData( ).GetBytes( ) );

      return basicData;
    }



  }
}
